package com.it.you.base.string;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class StringTest4 {
    public static void main(String[] args) {
        calculate();
    }

    public static void calculate() {
        List<Integer> types = Arrays.asList(1, 2, 3, 4);
        while (true) {
            System.out.println("请输入第一个数字：");
            Scanner scanner = new Scanner(System.in);
            String firstNum = scanner.next();
            if ("exit".equals(firstNum)) {
                System.exit(0);
            }
            System.out.println("请输入第二个数字：");
            String secondNum = scanner.next();
            if ("exit".equals(secondNum)) {
                System.exit(0);
            }
            System.out.println("请选择运算种类：1-加法；2-减法；3-乘法；4-除法");
            int type = scanner.nextInt();
            while (!types.contains(type)) {
                System.out.println("请重新选择运算种类：1-加法；2-减法；3-乘法；4-除法");
                type = scanner.nextInt();
            }
            String sum = handle(firstNum, secondNum, type);
            String calType = type == 1 ? "+" : type == 2
                    ? "−" : type == 3
                    ? "×" : type == 4
                    ? "÷" : null;
            System.out.println("运算结果为：" + firstNum + calType + secondNum + "=" + sum);
        }
    }

    public static String handle(String num1, String num2, Integer type) {
        //switch与case连用，case的语句体要写return 或者 break 不然会发生穿透
        switch (type) {
            case 1:
                return new BigDecimal(num1).add(new BigDecimal(num2)).stripTrailingZeros().toPlainString();
            case 2:
                return new BigDecimal(num1).subtract(new BigDecimal(num2)).stripTrailingZeros().toPlainString();
            case 3:
                return new BigDecimal(num1).multiply(new BigDecimal(num2)).stripTrailingZeros().toPlainString();
            case 4:
                while (num2 == null || "0".equals(num2)) {
                    System.out.println("除数不能为0，请重新输入");
                    Scanner scanner = new Scanner(System.in);
                    num2 = scanner.next();
                }
                return new BigDecimal(num1).divide(new BigDecimal(num2), 8, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
        }
        return null;
    }

}
